#include "MainWindow.h"
#include "ui_mainwindow.h"
#include "CameraThread.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, &MainWindow::triggerCapture);
    connect(ui->btnStart, &QPushButton::clicked, this, &MainWindow::onStart);
    connect(ui->btnStop,  &QPushButton::clicked, this, &MainWindow::onStop);
}

MainWindow::~MainWindow()
{
    onStop();
    delete ui;
}

void MainWindow::onStart()
{
    if (m_cam0 || m_cam1) return;          // 防止重复启动
    m_cam0 = new CameraThread(0, &m_mutex, &m_trigger, this);
    m_cam1 = new CameraThread(1, &m_mutex, &m_trigger, this);
    connect(m_cam0, &CameraThread::frameReady, this, &MainWindow::updateCam0);
    connect(m_cam1, &CameraThread::frameReady, this, &MainWindow::updateCam1);
    m_cam0->start();
    m_cam1->start();
    m_timer->start(200);
    ui->labelStatus->setText("Running");
}

void MainWindow::onStop()
{
    m_timer->stop();
    if (m_cam0) {
        m_cam0->requestStop();
        m_cam0->deleteLater();
        m_cam0 = nullptr;
    }
    if (m_cam1) {
        m_cam1->requestStop();
        m_cam1->deleteLater();
        m_cam1 = nullptr;
    }
    ui->labelStatus->setText("Stopped");
}

void MainWindow::triggerCapture()
{
    m_trigger.wakeAll();
    ui->ledTrigger->setStyleSheet("color: green; font-size:24px;");
    QTimer::singleShot(100, [this](){
        ui->ledTrigger->setStyleSheet("color: gray; font-size:24px;");
    });
}

void MainWindow::updateCam0(const QImage &img)
{
    ui->labelCam0->setPixmap(QPixmap::fromImage(img.scaled(320,240,Qt::KeepAspectRatio)));
}
void MainWindow::updateCam1(const QImage &img)
{
    ui->labelCam1->setPixmap(QPixmap::fromImage(img.scaled(320,240,Qt::KeepAspectRatio)));
}
